<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--搜索-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['wx:banner:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['wx:banner:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['wx:banner:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" ref="multipleTable" :data="tableDataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="图片" align="center" >
            <template slot-scope="scope">
              <img :src="baseUrl + scope.row.url" width="40" height="40" />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" key="status">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="2"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['wx:banner:edit']"
              >修改</el-button>
              <el-button
                v-if="scope.row.id !== 0"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['wx:banner:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form"  label-width="80px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="上传图片"></el-form-item>
          </el-col>

          <el-col :span="12">
            <el-upload
              class="upload-demo"
              action=""
              :http-request="uploadBanner"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :limit="imgNum"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
            </el-upload>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBanner, addBanner, updateBanner, delBanner,upload,changeStatus} from "@/api/wx/banner/banner";

export default {
  name: "Banner",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表格数据
      tableDataList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,


      // 搜索查询状态数据字典
      statusOptions: [
        {
          "label": "启用",
          "value": "1"
        },{
          "label": "禁用",
          "value": "2"
        }
      ],

      multipleTable: [],


      // 表单参数
      form: {
        id: undefined,
        url:'',
        status: '1'
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "",
      },

      //图片
      fileList: [],
      imgNum: 1,

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        let data = response.data;
        let list = data.records;
        list.forEach(d=>{
          d.status = d.status + '';
        })
        this.tableDataList = list;
        this.total = data.total;
        this.loading = false;
        }
      );
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },



    handlePreview(file) {
      console.log(file);
    },

    uploadBanner(item){
      const isLt1M = item.file.size / 1024 / 1024 < 2
      if (!isLt1M) {
        this.msgError('上传的图片不能超过2M')
      }
      if (isLt1M === true) {
        let params = new FormData()
        params.append('file', item.file)
        upload(params).then(res =>{
          console.log(res)
          if (res.code === 200){
            this.form.url = res.data;
          }
        })
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        status: "1",
        url: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      if (this.queryParams.createTime == null){
        this.queryParams.createTime = "";
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.multipleTable = selection;               //  this.multipleTable 选中的值
    },

    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '"该图片吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeStatus({"id":row.id, "status":row.status});
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "1" ? "2" : "1";
      });
    },



    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图片";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fileList = [];
      this.open = true;
      this.title = "修改图片";
      const keyId = row.id || this.ids[0];
      //选择框修改
      if (typeof row.id === 'undefined'){
        for (let i = 0; i < this.multipleTable.length; i++) {
          const halo = this.multipleTable[i];
          if (halo.id === keyId){
            row = halo;
          }
        }
      }
      this.fileList.push({name:row.id,url:this.baseUrl + row.url});
      this.form.id = keyId;
      this.form.url = row.url;
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateBanner(this.form).then(res =>{
              this.msgSuccess("更新成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanner(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const keyId = [];
      //选择框删除
      if (typeof row.id === 'undefined'){
        for (let i=0;i<this.ids.length;i++){
          keyId.push(this.ids[i]);
        }
      }else {
        keyId.push(row.id);
      }
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delBanner({"ids":keyId});
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },

  }
};
</script>
